package org.noote.tools;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class FileChooser extends Activity {

	public static String TITLE = "title";
	public static String DESCRIPTION = "description";
	public static String ACTION = "action";
	public static String FILENAME = "filename";

	public static int GET_SINGLEFILE = 0;
	public static int GET_PATH = 1;

	private File m_CurrentDir;
	private FileArrayAdapter m_Adapter;
	private int m_iCurrentAction = 0;

	public class Option implements Comparable<Option> {
		static final int TYPE_PARENT_DIR = 0;
		static final int TYPE_DIR = 1;
		static final int TYPE_FILE = 2;
		
		private int type;
		private String name;
		private String data;
		private String path;

		public Option(int t, String n, String d, String p) {
			type = t;
			name = n;
			data = d;
			path = p;
		}

		public int getType() {
			return type;
		}
		
		public String getName() {
			return name;
		}

		public String getData() {
			return data;
		}

		public String getPath() {
			return path;
		}

		@Override
		public int compareTo(Option o) {
			if (this.name != null)
				return this.name.toLowerCase().compareTo(
						o.getName().toLowerCase());
			else
				throw new IllegalArgumentException();
		}
	};

	public class FileArrayAdapter extends ArrayAdapter<Option> {

		private Context c;
		private int id;
		private List<Option> items;

		public FileArrayAdapter(Context context, int textViewResourceId,
				List<Option> objects) {
			super(context, textViewResourceId, objects);
			c = context;
			id = textViewResourceId;
			items = objects;
		}

		@Override
		public Option getItem(int i) {
			return items.get(i);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) c
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(id, null);
			}
			final Option o = items.get(position);
			if (o != null) {
				TextView t1 = (TextView) v.findViewById(R.id.TextView01);
				TextView t2 = (TextView) v.findViewById(R.id.TextView02);

				if (t1 != null)
					t1.setText(o.getName());
				if (t2 != null)
					t2.setText(o.getData());

			}
			return v;
		}

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.filechooser);

        ListView listFiles = (ListView)findViewById(R.id.listFiles);
        listFiles.setOnItemClickListener(new OnItemClickListener() {
        	@Override
            public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
        		Option o = m_Adapter.getItem(position);
        		if (o.getType() == Option.TYPE_FILE) {
        			if(m_iCurrentAction == GET_SINGLEFILE)
        				onFileClick(o.getPath());
        		} else {
        			m_CurrentDir = new File(o.getPath());
        			fill(m_CurrentDir);
        		}
        	}
        });
        Button buttonSelect = (Button)findViewById(R.id.buttonSelect);
        buttonSelect.setOnClickListener(new OnClickListener()
        {
			@Override
			public void onClick(View arg0) {
				if(m_iCurrentAction == GET_PATH)
				{
					TextView textCurrentPath = (TextView)findViewById(R.id.textCurrentPath);
					String sPath = textCurrentPath.getText().toString();
					onDirClick(sPath);
				}
			}
        });
        
		m_CurrentDir = new File("/");

		Bundle bundle = this.getIntent().getExtras();
		String sTitle = bundle.getString(TITLE);
		if(sTitle != null && sTitle.length()>0)
			setTitle(sTitle);
		String sDesc = bundle.getString(DESCRIPTION);
		if(sDesc != null && sDesc.length()>0)
		{
			TextView textDescription = (TextView)findViewById(R.id.textDescription);
			textDescription.setText(sDesc);
		}
		else
		{
			TextView textDescription = (TextView)findViewById(R.id.textDescription);
			textDescription.setVisibility(View.GONE);
		}
		
		int iAction = bundle.getInt(ACTION);
		if (iAction == GET_PATH)
		{
			m_iCurrentAction = GET_PATH;
			String sFilename = bundle.getString(FILENAME);
			File tryFile = new File(sFilename);
			if (tryFile.exists()) {
				if (tryFile.isFile()) {
					m_CurrentDir = tryFile.getParentFile();
				} else {
					m_CurrentDir = tryFile;
				}
			}
		}
		else //if (iAction == GET_SINGLEFILE)
		{
			m_iCurrentAction = GET_SINGLEFILE;
			String sFilename = bundle.getString(FILENAME);
			File tryFile = new File(sFilename);
			if (tryFile.exists()) {
				if (tryFile.isFile()) {
					m_CurrentDir = tryFile.getParentFile();
				} else {
					m_CurrentDir = tryFile;
				}
			}
			View layoutActionButtons = findViewById(R.id.layoutActionButtons);
			layoutActionButtons.setVisibility(View.GONE);			
		}

		fill(m_CurrentDir);
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.filechooser_menu, menu);
        return true;
    }
    
    /* Handles item selections */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==R.id.itemCreateDir)
        {
            CreateDir();
            return true;
        }
        return false;
    }

    private void CreateDir() {
    	final EditText input = new EditText(this);
    	new AlertDialog.Builder(FileChooser.this)
        .setTitle("Create a dir")
        .setView(input)
        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
			public void onClick(DialogInterface dialog, int whichButton) {
            	TextView textCurrentPath = (TextView)findViewById(R.id.textCurrentPath);
            	String sCurDir = textCurrentPath.getText().toString();
                String sValue = input.getText().toString();
                
    			File dirExport = new File(sCurDir+"/"+sValue);
    			if (!dirExport.exists())
    			{
    				dirExport.mkdirs();
        			fill(dirExport);
    			}
            }
        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
			public void onClick(DialogInterface dialog, int whichButton) {
                // Do nothing.
            }
        }).show();
	}

	private void fill(File f) {
		ListView listFiles = (ListView)findViewById(R.id.listFiles);

		TextView textCurrentPath = (TextView)findViewById(R.id.textCurrentPath);
		textCurrentPath.setText(f.getAbsolutePath());
		
		File[] dirs = f.listFiles();
		
		List<Option> dir = new ArrayList<Option>();
		List<Option> fls = new ArrayList<Option>();
		try {
			for (File ff : dirs) {
				if (ff.isDirectory())
					dir.add(new Option(Option.TYPE_DIR, ff.getName(), getString(R.string.folder), ff.getAbsolutePath()));
				else {
					fls.add(new Option(Option.TYPE_FILE, ff.getName(), getString(R.string.filesize, ff.length()), ff.getAbsolutePath()));
				}
			}
		} catch (Exception e) {

		}
		Collections.sort(dir);
		Collections.sort(fls);
		dir.addAll(fls);
		if (!f.getName().equalsIgnoreCase("/"))
			dir.add(0, new Option(Option.TYPE_PARENT_DIR, "<..>", getString(R.string.parent_directory), f.getParent()));
		
		m_Adapter = new FileArrayAdapter(FileChooser.this,
				R.layout.filechooser_view_item, dir);
		
		listFiles.setAdapter(m_Adapter);
	}

	private void onFileClick(String sFile) {
    	Bundle bundle = new Bundle();
    	bundle.putString(FILENAME, sFile);
		Intent intent = new Intent();
		intent.putExtras(bundle);
		setResult(RESULT_OK, intent);
		finish();
	}
	protected void onDirClick(String sPath) {
 		Bundle bundle = new Bundle();
    	bundle.putString(FILENAME, sPath);
		Intent intent = new Intent();
		intent.putExtras(bundle);
		setResult(RESULT_OK, intent);
		finish();
	}
}